﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using CeA.Reports.Atendimento.DataAccess;
using CeA.Reports.Atendimento.DataAccess.Criteria;
using CeA.Reports.Atendimento.DataAccess.DAO;
using CeA.Reports.Atendimento.DataAccess.Helpers;
using CeA.Reports.Atendimento.DataAccess.Model;
using CeA.Reports.Atendimento.Web.WebControls;
using libFusion.data;
using InfoSoftGlobal;

namespace CeA.Reports.Atendimento.Web.site {
    public partial class relatorioTempoAtendimento : System.Web.UI.Page {
        List<TempoAtendimento> m_source = null;
        List<TempoAtendimento> m_sourceTotalPorRfs = null;
        DataTable dtFooter = new DataTable();
        int indexFooter = 0;

        protected void Page_Init(object sender, EventArgs e)                                {
            filtroHierarquico.Pesquisar += new CeA.Reports.Atendimento.Web.WebControls.FiltroHierarquico.PesquisarEventHandler(filtroHierarquico_Pesquisar);
        }

        
        protected void filtroHierarquico_Pesquisar(object sender, PesquisarEventArgs e)     {
            report.Visible = true;
            carregarListaRegionais(e.Filter);
            carregarTotalNacional(e.Filter);
            carregarTotalPorRfs(e.Filter);
            btnExportarExcel.Visible = true;
            pnlImprimir.Visible = true;

            //if (e.ExportarRelatorio == true) {  
            //}

            if (e.GerarGrafico == true) {
                graph1Container.Visible = true;
                graph2Container.Visible = true;
                graph3Container.Visible = true;
                graph4Container.Visible = true;
                graph5Container.Visible = true;
                gerarGrafico(e.Filter.DataInicial, e.Filter.DataFinal);
            }
        }


        protected void Page_Load(object sender, EventArgs e)                                {

        }


        private void carregarListaRegionais(TempoAtendimentoFilter filter)                  {
            DAOFactory factory = DAOFactory.GetDAOFactory(DAOFactoryType.ORACLE);
            RelatorioTempoAtendimento dao = factory.GetRelatorioTempoEsperaDAO();

            dtFooter.Columns.Add("regiao");                         //-> 0
            dtFooter.Columns.Add("senhaRetiradas");                 //-> 1
            dtFooter.Columns.Add("senhasAtendidas");                //-> 2
            dtFooter.Columns.Add("quantidadeDesistencia");          //-> 3
            dtFooter.Columns.Add("porcentagemDesistencia");         //-> 4
            dtFooter.Columns.Add("tempoMedioEspera");               //-> 5 
            dtFooter.Columns.Add("tempoMaximoEspera");              //-> 6
            dtFooter.Columns.Add("porcentagemAtendimentoIdeal");    //-> 7
            dtFooter.Columns.Add("tempoMedioAtendimento");          //-> 8
            dtFooter.Columns.Add("tempoMaximoAtendimento");         //-> 9

            dtFooter.Columns.Add("tempoMedioEsperaSegundos");       //-> 10 [5]
            dtFooter.Columns.Add("tempoMedioAtendimentoSegundos");  //-> 11 [8]
            
            m_source = dao.FindTempoMedioAtendimentoBy(filter);

            List<String> regiaoList = new List<String>();
            String auxSiglaRegiao = null;
            foreach (TempoAtendimento item in m_source) {
                if (auxSiglaRegiao != item.SiglaRegiao) {
                    auxSiglaRegiao = item.SiglaRegiao;
                    regiaoList.Add(item.SiglaRegiao);
                }
            }

            dtlRegionais.DataSource = regiaoList;
            dtlRegionais.DataBind();
        }


        private void carregarTotalNacional(TempoAtendimentoFilter filter)                   {

            DAOFactory factory = DAOFactory.GetDAOFactory(DAOFactoryType.ORACLE);
            RelatorioTempoAtendimento dao = factory.GetRelatorioTempoEsperaDAO();

            /*
            TempoAtendimentoFilter filter = new TempoAtendimentoFilter(40,
                new DateTime(2009, 1, 1, 0, 0, 0), new DateTime(2010, 1, 1, 23, 59, 59));
            */

            TempoAtendimento row = dao.GetTempoAtendimentoNacionalBy(filter);
            List<TempoAtendimento> m_source = new List<TempoAtendimento>();
            m_source.Add(row);

            dtlTotalNacional.DataSource = m_source;
            dtlTotalNacional.DataBind();
            
        }


        private void carregarTotalPorRfs(TempoAtendimentoFilter filter)                     {
            DAOFactory factory = DAOFactory.GetDAOFactory(DAOFactoryType.ORACLE);
            RelatorioTempoAtendimento dao = factory.GetRelatorioTempoEsperaDAO();

            m_sourceTotalPorRfs = dao.FindTempoAtendimentoRfsBy(filter);

            dtlTotalPorRfs.DataSource = m_sourceTotalPorRfs;
            dtlTotalPorRfs.DataBind();
        }


        protected void dtlLojas_Totalizador(object sender, DataListItemEventArgs e)         {

            if (e.Item.ItemType == ListItemType.Footer) {
                Label lblRegiao = (Label)e.Item.FindControl("lblRegiaoSigla");
                lblRegiao.Text = dtFooter.Rows[indexFooter][0].ToString();

                Label lblsr = (Label)e.Item.FindControl("lblSenhaRetirada");
                lblsr.Text = dtFooter.Rows[indexFooter][1].ToString();

                Label lblsa = (Label)e.Item.FindControl("lblSenhaAtendida");
                lblsa.Text = dtFooter.Rows[indexFooter][2].ToString();

                Label lblqd = (Label)e.Item.FindControl("lblQtdeDesistencia");
                lblqd.Text = dtFooter.Rows[indexFooter][3].ToString();

                Label lblpd = (Label)e.Item.FindControl("lblPorcentagemDesitencia");
                lblpd.Text = dtFooter.Rows[indexFooter][4].ToString();

                Label lbltmee = (Label)e.Item.FindControl("lblTempoMedEspera");
                lbltmee.Text = dtFooter.Rows[indexFooter][5].ToString();

                Label lbltmae = (Label)e.Item.FindControl("lblTempoMaxEspera");
                lbltmae.Text = dtFooter.Rows[indexFooter][6].ToString();

                Label lblqtei = (Label)e.Item.FindControl("lblQuantidadeTempoEsperaIdeal");
                lblqtei.Text = dtFooter.Rows[indexFooter][7].ToString();

                Label lbltmea = (Label)e.Item.FindControl("lblTempoMedAtendimento");
                lbltmea.Text = dtFooter.Rows[indexFooter][8].ToString();

                Label lbltmaa = (Label)e.Item.FindControl("lblTempoMaxAtendimento");
                lbltmaa.Text = dtFooter.Rows[indexFooter][9].ToString();
            }

        }


        protected void dtlRegionais_ItemDataBound(object sender, DataListItemEventArgs e)   {

            DataRow drData = null;
           
            int senhasRetiradas = 0;
            int senhasAtendidas = 0;
            int quantidadeDesistencias = 0;
            int tempoTotalEspera = 0;
            int tempoMaximoEspera = 0;
            int quantidadeAtendimentoEsperaIdeal = 0;
            int tempoTotalAtendimento = 0;
            int tempoMaximoAtendimento = 0;

            drData = dtFooter.NewRow();
          

            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
                DataList dtlLojas = (DataList)e.Item.FindControl("dtlLojas");
                string regiaoLabel = ((Label)e.Item.FindControl("regiaoLabel")).Text;
                dtlLojas.DataSource = m_source.FindAll(delegate(TempoAtendimento rows) {
                    if (rows.SiglaRegiao == regiaoLabel)
                    {
                        
                        senhasRetiradas += rows.SenhasRetiradas;
                        senhasAtendidas += rows.SenhasAtendidas;
                        quantidadeDesistencias += rows.QuantidadeDesistencias;
                        tempoTotalEspera += (rows.TempoEspera * rows.SenhasRetiradas);
                        if (tempoMaximoEspera < rows.TempoMaximoEspera) { tempoMaximoEspera = rows.TempoMaximoEspera; }
                        quantidadeAtendimentoEsperaIdeal += rows.QuantidadeTempoEsperaIdeal;
                        tempoTotalAtendimento += (rows.Tempo * rows.SenhasRetiradas);
                        if (tempoMaximoAtendimento < rows.TempoMaximoAtendimento) { tempoMaximoAtendimento = rows.TempoMaximoAtendimento; }
                        return true;
                    }
                    else
                        return false;
                });
                drData[0] = regiaoLabel;
                drData[1] = senhasRetiradas;
                drData[2] = senhasAtendidas;
                drData[3] = quantidadeDesistencias;
                drData[4] = ((quantidadeDesistencias / (float) senhasRetiradas) * 100).ToString("F");
                drData[5] = ConvertHelper.SecondToHour((int)(tempoTotalEspera / senhasRetiradas));
                drData[6] = ConvertHelper.SecondToHour(tempoMaximoEspera);
                drData[7] = ((quantidadeAtendimentoEsperaIdeal /(float) senhasAtendidas) * 100).ToString("F");
                drData[8] = ConvertHelper.SecondToHour((int)(tempoTotalAtendimento / senhasRetiradas));
                drData[9] = ConvertHelper.SecondToHour(tempoMaximoAtendimento);

                drData[10] = (int)(tempoTotalEspera / senhasRetiradas);         //-- tempoMedioEsperaSegundos
                drData[11] = (int)(tempoTotalAtendimento / senhasRetiradas);    //-- tempoMedioAtendimentoSegundos

                dtFooter.Rows.Add(drData);
                dtlLojas.DataBind();
                indexFooter += 1;                
            }
        }


        protected void exportarToExcel(object sender, EventArgs e)                          {
            string filename = "RelatorioIndicadores.xls";
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(1));
            Response.ContentType = "application/vnd.ms-excel";
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());
            Response.Charset = "";
            this.EnableViewState = false;
            Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
            Response.Write("\r\n");
            Response.Write("<style> .text " + "\r\n" + " {mso-style-parent:style0;mso-number-format:\"" + @"\@" + "\"" + ";} " + "\r\n" + "</style>");
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            report.RenderControl(hw);
            //dtlRegionais.RenderControl(hw);
            //dtlTotalNacional.RenderControl(hw);
            //dtlTotalPorRfs.RenderControl(hw);
            Response.AppendHeader("content-disposition", "attachment;filename=" + filename);
            Response.Write(tw.ToString());
            Response.End();
        }


        protected void imprimir(object sender, EventArgs e)                                 {
            string filename = "RelatorioIndicadores.html";
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(1));
            Response.ContentType = "application/vnd.ms-html";
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());
            Response.Charset = "";
            this.EnableViewState = false;
            Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:html\">");
            Response.Write("\r\n");
            Response.Write("<style> .text " + "\r\n" + " {mso-style-parent:style0;mso-number-format:\"" + @"\@" + "\"" + ";} " + "\r\n" + "</style>");
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            report.RenderControl(hw);
            //dtlEspecialistas.RenderControl(hw);
            //dtlTotalNacional.RenderControl(hw);
            //dtlTotalPorRfs.RenderControl(hw);
            Response.AppendHeader("content-disposition", "attachment;filename=" + filename);
            Response.Write(tw.ToString());
            Response.End();
        }


        private void gerarGrafico(DateTime dataInicial, DateTime dataFinal)                 {
            /*** Grafico 1: Quantidade de Atendimento           *** Gráfico 2: Tempo Atendimento
             * [0] Regiao                                       * [ 0] Regiao
             * [1] Senhas Retiradas                             * [10] Tempo Médio de Espera
             * [2] Clientes Atendidos                           * [11] Tempo Médio de Atendimento
             * [3] Número de Desistências                       * [ 7] % Clientes Atendidos em menos de 15 minutos
             * [4] Porcentagem de Desistências
             */


            string quote = Server.HtmlEncode("%");

            DataTable graph1 = new DataTable("GRAPH1");

            graph1.Columns.Add(new DataColumn("regiao", typeof(string)));
            graph1.Columns.Add(new DataColumn("Senhas Retiradas", typeof(int)));
            graph1.Columns.Add(new DataColumn("Clientes Atendidos", typeof(int)));
            graph1.Columns.Add(new DataColumn("Numero de Desistências", typeof(int)));
            graph1.Columns.Add(new DataColumn(quote + " %25 Desistencias", typeof(int)));

            DataTable graph2 = new DataTable("GRAPH2");
            graph2.Columns.Add(new DataColumn("regiao", typeof(string)));
            graph2.Columns.Add(new DataColumn("Tempo M. Espera", typeof(int)));
            graph2.Columns.Add(new DataColumn("Tempo M. Atendimento", typeof(int)));
            graph2.Columns.Add(new DataColumn(quote + " %25 Clientes Atendidos até 15 minutos de Espera", typeof(int)));


            foreach (DataRow dr in dtFooter.Rows) {
                DataRow graph1Row = graph1.NewRow();
                graph1Row[0] = dr[0];   // Regiao
                graph1Row[1] = dr[1];   // Senhas Retiradas
                graph1Row[2] = dr[2];   // Clientes Atendidos
                graph1Row[3] = dr[3];   // Numero Desistências
                graph1Row[4] = (int)Convert.ToDecimal(dr[4]);  // Percentual Desistências
                graph1.Rows.Add(graph1Row);

                DataRow graph2Row = graph2.NewRow();
                graph2Row[0] = dr[ 0];   // Regiao
                graph2Row[1] = dr[10];   // Tempo M. Espera
                graph2Row[2] = dr[11];   // Tempo M. Atendimento
                graph2Row[3] = (int)Convert.ToDecimal(dr[ 7]); // %Clientes Atendidos até 15 min.
                graph2.Rows.Add(graph2Row);
            }

            //--
            //-- 1o. Gráfico: Quantidade de Atendimento
            //--
            FusionMSColumn3DLineDYChart chart1 = new FusionMSColumn3DLineDYChart();
            chart1.ChartPath = "/charts";
            chart1.Caption = "Senhas Retiradas vs Clientes Atendidos";
            chart1.SubCaption = string.Format("Período de {0} à {1}", dataInicial.ToString(), dataFinal.ToString());
            chart1.PYAxisName = "Quantidade";
            chart1.SYAxisName = quote + " %25 de Desistências";
            chart1.XAxisName = "Regional";
            chart1.Showvalues =  false;
            chart1.ShowXValues = false;
            chart1.RotateValues = true;
            chart1.PosicaoInicioEixoY = 4;
            chart1.FormatNumberScale = false;
          
            chart1.ShowYAxisValues = true;
            chart1.NumberScaleValue = "";
            chart1.NumberScaleUnit = "";
            chart1.DefaultNumberScale = "";
            chart1.SFormatNumber = true;
            chart1.SnumberScaleUnit = "";
            chart1.SNumberSuffix = "%25";
            chart1.SDecimals = "2";
            chart1.SYAxisMaxValue = 20;
          
            
            

            graph1Container.InnerHtml = chart1.CreateSetElement(graph1, FusionMSColumn3DLineDYChart.MSColumn3DLineDY, graph1Container.ClientID, 908, 404);

            //--
            //-- 2o. Gráfico: Tempo Atendimento
            //--
            FusionMSColumn3DLineDYChart chart2 = new FusionMSColumn3DLineDYChart();
            chart2.ChartPath = "/charts";
            chart2.Caption = "Tempo Médio de Espera e Atendimento";
            chart2.SubCaption = string.Format("Período de {0} à {1}", dataInicial.ToString(), dataFinal.ToString());
            chart2.PYAxisName = "Tempo de Médio Espera e Atendimento";
            chart2.SYAxisName = "%25 Clientes Atendidos em até 15 min de Espera";
            chart2.XAxisName = "Regional";
            chart2.RotateValues = false;
            chart2.Showvalues = false;
            chart2.ShowYValues = true;
            chart2.ShowXValues = false;
            chart2.ShowYAxisValues = true;  
            chart2.PosicaoInicioEixoY = 3;
            chart2.FormatNumberScale = true;

            chart2.NumberScaleValue = "60,60,24,7";
            chart2.NumberScaleUnit = "min,hr,day,wk";
            chart2.DefaultNumberScale = "s";
            chart2.SFormatNumber = true;
            chart2.SnumberScaleUnit = "";
            chart2.SNumberSuffix = "%25";
            chart2.SDecimals = "2";
            

            graph2Container.InnerHtml = chart2.CreateSetElement(graph2, FusionMSColumn3DLineDYChart.MSColumn3DLineDY, graph2Container.ClientID, 908, 404);

            //-- ------------------------------------------------------------------------------------------------------
            //-- 3o. Gráfico: Tempo Médio
            //-- TODO: Refactor this method in the future.
            //-- ------------------------------------------------------------------------------------------------------
            DataTable graph3 = new DataTable("GRAPH2");
            graph3.Columns.Add(new DataColumn("RFS", typeof(string)));
            graph3.Columns.Add(new DataColumn("Tempo M. Espera", typeof(int)));
            graph3.Columns.Add(new DataColumn("Tempo M. Atendimento", typeof(int)));
            graph3.Columns.Add(new DataColumn(" %25 Clientes Atendidos até 15 minutos de Espera", typeof(string)));

            foreach (TempoAtendimento dr in m_sourceTotalPorRfs) {
                DataRow graph3Row = graph3.NewRow();
                graph3Row[0] = dr.NomeRfs;
                graph3Row[1] = dr.TempoEspera;  // Tempo Medio Espera
                graph3Row[2] = dr.Tempo;        // Tempo Medio Atendimento
                graph3Row[3] = (int)Convert.ToDecimal(dr.QuantidadeTempoEsperaIdealString); // %Clientes Atendidos até 15 min.
                graph3.Rows.Add(graph3Row);
            }

            FusionMSColumn3DLineDYChart chart3 = new FusionMSColumn3DLineDYChart();
            chart3.ChartPath = "/charts";
            chart3.Caption = "Tempo Médio de Espera e Atendimento";
            chart3.SubCaption = string.Format("Período de {0} à {1}", dataInicial.ToString(), dataFinal.ToString());
            chart3.PYAxisName = "Tempo de Médio de Espera e Atendimento";
            chart3.SYAxisName = "  %25 Clientes Atendidos até 15 minutos de Espera";
            chart3.XAxisName = "RFS";            
            chart3.RotateValues = false;
            chart3.PosicaoInicioEixoY = 3;
            chart3.FormatNumberScale = true;

            chart3.NumberScaleValue = "60,60,24,7";
            chart3.NumberScaleUnit = "min,hr,day,wk";
            chart3.DefaultNumberScale = "s";
            chart3.SFormatNumber = true;
            chart3.SnumberScaleUnit = "";
            chart3.SNumberSuffix = "%25";
            chart3.SDecimals = "2";


            graph3Container.InnerHtml = chart3.CreateSetElement(graph3, FusionMSColumn3DLineDYChart.MSColumn3DLineDY, graph2Container.ClientID, 908, 404);


            //-- ------------------------------------------------------------------------------------------------------
            //-- 4o. Gráfico: Atendimento por RFS s
            //-- TODO: Refactor this method in the future.
            //-- ------------------------------------------------------------------------------------------------------
            //xmlData will be used to store the entire XML document generated
            StringBuilder xmlDataAtendidos = new StringBuilder();
            //Generate the chart element
            xmlDataAtendidos.Append("<chart caption='Clientes Atendidos' subCaption='" + string.Format("Período de {0} à {1}", dataInicial.ToString(), dataFinal.ToString()) + "'     pieSliceDepth='30' showBorder='1' formatNumberScale='0' showPercentInToolTip='1' showPercentValues='1' showLabels='1'  showValues='1'  numberSuffix=' atendimentos'>");

            foreach (TempoAtendimento dr in m_sourceTotalPorRfs)
            {
                xmlDataAtendidos.AppendFormat("<set label='{0}' value='{1}' />", dr.NomeRfs + '[' + dr.SenhasAtendidas + ']', dr.SenhasAtendidas);
            }
            xmlDataAtendidos.Append("</chart>");
            graph4Container.InnerHtml = FusionCharts.RenderChartHTML("/charts/Pie3D.swf", "pieAtendimento", xmlDataAtendidos.ToString(), "", "900", "400", false);

            

            //-- ------------------------------------------------------------------------------------------------------
            //-- 5o. Gráfico: Desistencia
            //-- TODO: Refactor this method in the future.
            //-- ------------------------------------------------------------------------------------------------------
            DataTable graph5 = new DataTable("GRAPH5");
            graph5.Columns.Add(new DataColumn("RFS", typeof(string)));
            graph5.Columns.Add(new DataColumn("Clientes Atendidos", typeof(int)));
            graph5.Columns.Add(new DataColumn("Desistencia", typeof(int)));
            
            foreach (TempoAtendimento dr in m_sourceTotalPorRfs)
            {
                DataRow graph5Row = graph5.NewRow();
                graph5Row[0] = dr.NomeRfs;
                graph5Row[1] = dr.SenhasAtendidas;
                graph5Row[2] = dr.PorcentagemDesistencias;
                graph5.Rows.Add(graph5Row);
            }

            FusionMSColumn3DLineDYChart chart5 = new FusionMSColumn3DLineDYChart();
            chart5.ChartPath = "/charts";
            chart5.Caption = "Clientes Atendidos vs Desistentes";
            chart5.SubCaption = string.Format("Período de {0} à {1}", dataInicial.ToString(), dataFinal.ToString());
            chart5.PYAxisName = "Quantidade Atendimento";
            chart5.SYAxisName = "%25 de Desistencia";
            chart5.XAxisName = "RFS";
            chart5.RotateValues = false;
            chart5.PosicaoInicioEixoY = 2;
            chart5.FormatNumberScale = false;
            chart5.NumberScaleValue = "";
            chart5.NumberScaleUnit = "";
            chart5.InDecimalSeparator = ",";
            chart5.InThousandSeparator = ".";

            chart5.DefaultNumberScale = "";
            chart5.SFormatNumber = true;
            chart5.SnumberScaleUnit = "";
            chart5.SNumberSuffix = "%25";
            chart5.SDecimals = "2";
            chart5.SYAxisMaxValue = 20;


            

            graph5Container.InnerHtml = chart5.CreateSetElement(graph5, FusionMSColumn3DLineDYChart.MSColumn3DLineDY, graph5Container.ClientID, 908, 404);
            
        }
    }
}
